var HEIGHT = document.documentElement.clientHeight;
var WIDTH = document.documentElement.clientWidth;
if(WIDTH<1000)WIDTH=1000;
IS_SHOW_TRASH = false;
SAVING_FLAG = 0;
$(function() {
	GRID_QUERYOBJ = {};//查询条件
	loadGrid();
	initSearch();
	initUploadSimple({showDelBtn:true});//调用完整方法
	//paramMapData();
});

/**加载用户列表*/
function loadGrid(){
	$('#datagrid').datagrid({
	    url:'/back/getAuctionQuickList',
	    pagination:true,//允许分页
		pageSize:20,//每页10条数据
		loadMsg:'',
		width:WIDTH-1,
		height:HEIGHT-125,
		idField:'id',
		sortName:'addTime',
		sortOrder:'DESC',
		queryParams:GRID_QUERYOBJ,
		fitColumns:false,
		selectOnCheck:false,
		checkOnSelect:false,
		singleSelect:true,
		striped:true,
	    columns:[
		[
			{field:'checkbox',title:'多选框',checkbox:true},
			{field:'id',title:'',hidden:true},
	        {field:'instName',title:'机构名称',width:200,align:'center',formatter: function(value,row,index){
	        	if(!value)return '';
				var dom = '<span>'+value+'</span>' +
				'<button class="copy_btn pointer fr" data-clipboard-text="'+row.instSerial+'">复制编号</button>';
	        	return dom;
	        }},
	        {field:'picPaths',title:'机构图标',width:140,align:'center',formatter: function(value,row,index){
	        	var logo = '<a href="'+value+'" target="_blank"><img style="height:40px;cursor:pointer;" src="'+value+'"/></a>';
	        	if(!value)logo = '<span style="line-height:40px;">暂无图标<span>';
	        	return logo;
	        }},
	        {field:'auctionName',title:'即时拍名称',width:140,align:'center'},
	        {field:'auctionSerial',title:'拍卖场次',width:140,align:'center'},
	        {field:'mainStatus',title:'状态',width:80,align:'center',formatter: function(value,row,index){
	        	var status;
	        	if(value == 1){status = '<span style="color:green">预展中</span>';}
	        	else if(value == 2){status = '<span style="color:#FF6000">正在进行中</span>';}
	        	else if(value == 3){status = '<span style="color:gray">已结束</span>';}
	        	return status;
	        }},
	        {field:'operate',title:'操作',width:100,align:'center',formatter: function(value,row,index){
	        	return '<span class="g_alive"><span class="opt_cuation" onclick="openAuctionQuickWin('+index+',\'update\')">修改</span>'+//jumpToAuctionQuickUpdate
	        		   ' |  <span class="opt_green" onclick="openAuctionQuickWin('+index+',\'read\')">查看</span></span>'+//jumpToAuctionQuick
	        		   '<span class="g_trash"><span class="opt_cuation" onclick="batchThoroughDelete('+row.id+')">彻底删除</span>'+
	        		   ' |  <span class="opt_green" onclick="batchRecover('+row.id+')">恢复</span></span>';
	        }},
	        {field:'startTime',title:'拍卖开始时间',width:120,align:'center',formatter: function(value,row,index){
	        	return formatDate(value,1);
	        }},
	        {field:'endTime',title:'拍卖结束时间',width:120,align:'center',formatter: function(value,row,index){
	        	return formatDate(value,1);
	        }},
	        {field:'joinNum',title:'参拍人数（人）',width:100,align:'center'},
	        {field:'visitNum',title:'围观次数（次）',width:100,align:'center'},
	        /*{field:'bail',title:'保证金（元）',width:100,align:'center'},
	        {field:'spreadPackets',title:'推广红包（元）',width:100,align:'center'},*/
	        {field:'createdAt',title:'添加时间',width:120,align:'center',formatter: function(value,row,index){
	        	return getDateStr(value);
	        }},
	        {field:'createdBy',title:'添加人',width:120,align:'center'},
	        {field:'updatedAt',title:'修改时间',width:120,align:'center',formatter: function(value,row,index){
	        	return getDateStr(value);
	        }},
	        {field:'updatedBy',title:'修改人',width:120,align:'center'},
	        {field:'deletedAt',title:'删除时间',width:120,align:'center',formatter: function(value,row,index){
	        	return getDateStr(value);
	        }},
	        {field:'deletedBy',title:'删除人',width:120,align:'center'}
	        ]],
	    /*,onSelect:function(rowIndex, rowData){onClickRowOfGrid(rowIndex, rowData);},
	    onClickRow: function(index, row){},
	    loadFilter: function(data){return data;},
		onLoadSuccess:function(data){} */
	        onLoadError: function(data){
		    	backDatagridErrorCheck(data);
		    },
		    onDblClickRow: function(index, row){
		    	openAuctionQuickWin(index, 'read');
	        },
	    onLoadSuccess:function(data){
	       	if(IS_SHOW_TRASH){
	       		$('.g_alive').hide();
	       		$('.g_trash').show();
	       	}else{
	       		$('.g_alive').show();
	       		$('.g_trash').hide();
	       	}
	       	initClipboard();//复制功能
	   }  
	});
}

/** grid 行点击事件 */
/**function onClickRowOfGrid(rowIndex, rowData){}*/

function loadCombo(){
	
	$('#f_mainStatus').combobox({
		valueField : 'id',
		textField : 'name',
		editable : false,
		multiple:false,
	    required:false,
	    panelHeight:'auto',
		data : [{
			'id' : 1,
			'name' : '已结束'
		},{
			'id' : 2,
			'name' : '预展中'
		},{
			'id' : 3,
			'name' : '正在进行中'
		}]
	});
	
}

/** 关闭窗口 */
function closeAuctionQuickWin(){
	$('#auctionQuickWin').window('close');
	//$('#datagrid').datagrid('clearSelections');
	//$('#datagrid').datagrid('clearChecked');
}

/** 提交表单 */
function submitAuctionQuick(){
	//$('#auctionQuickForm').submit();
	var timeRec = preventRepeat(10, SAVING_FLAG);
	if(timeRec){
		SAVING_FLAG = timeRec;
		$('#auctionQuickForm').submit();//执行操作
	}else{//重复提交
		return;//可进行提示或其他操作，这里直接返回，即重复提交时没有反应
	}
}

/** 添加用户 */
function addAuctionQuick(){
	openAuctionQuickWin(-1,'add');
}

/** 打开窗口 */
function openAuctionQuickWin(index,operation){
	$("#upload_outer_div").empty();
	var rows,data;
	if(index >= 0){
		rows = $('#datagrid').datagrid('getRows');
		data = rows[index];//获取该行的数据
	}
	var $form = $('#auctionQuickForm');
	
	$form.form({
	    url:'',
	    onSubmit: function(){
	       $('#auctionQuickForm').form('enableValidation');
	       var flag = $('#auctionQuickForm').form('validate');
	       var filePaths = $("#filePaths").val();
			var filePathArr = new Array();
			if(filePaths.indexOf(',') >= 0){
				filePaths = filePaths.substring(1);
			}
			if(!filePaths){$.messager.alert('提示','请上传商品图片');return;}
	       if(flag){
	       		var id;
	       		if(operation != 'add')id = data.id;
	       		var auctionQuick = getAuctionQuick(id);//得到用户信息的字段值
	       		auctionQuick.picPaths = filePaths;
	       	    $.post('/back/addOrUpdateAuctionQuick',auctionQuick,function(rsp){
					 if(rsp.success){
						 $('#datagrid').datagrid('reload');
						 //$('#datagrid').datagrid('clearSelections');
						 //$('#datagrid').datagrid('clearChecked');
				       	 setTimeout(function(){
				       		closeAuctionQuickWin();
				       	 },500);
					 }else{
						 $.messager.alert('提示',rsp.msg);
					 }
				},'json');
	       }
	       return false;
	    }
	});
	
	loadCombo();//加载下拉列表数据
	$('#auctionQuickWin').window('open');
	$form.form('clear');
	$form.form('disableValidation');
	$('#auctionQuickTip').html('');
	
	var domIds = "#f_auctionSerial,#f_bail,#f_spreadPackets,#f_startTime," +
				 "#f_endTime,#f_mainStatus,#f_joinNum,#f_visitNum,#f_auctionName";
	
	if(operation == 'add'){//添加
		$('#winSearchTr,#winSearchDivisionTr').show();//显示查询按钮
		$('#auctionQuickSave').show();
		$('#auctionQuickTable .readOnlyTr').hide();//隐藏只读字段
		$(domIds).textbox('readonly',false);//新增时设置为可编辑
	}else{//查看或修改
		$('#winSearchTr,#winSearchDivisionTr').hide();//隐藏查询按钮
		$('#auctionQuickTable .readOnlyTr').show();//显示只读字段
		var isReadOnly = false;
		if(operation == 'read'){//查看
			isReadOnly = true;
			$('#auctionQuickSave').hide();
		}else{//修改
			$('#auctionQuickSave').show();
		}
		$(domIds).textbox('readonly',isReadOnly);//设置只读还是可编辑
		setAuctionQuick(data);//设置用户详细信息字段值
	}
	
}

/** 得到用户信息的字段值 */
function getAuctionQuick(id){
	var auctionSerial = $('#f_auctionSerial').textbox('getValue');
	var auctionName = $('#f_auctionName').textbox('getValue');
	/*var bail = $('#f_bail').numberbox('getValue');
	var spreadPackets = $('#f_spreadPackets').numberbox('getValue');*/
	var startTime = $('#f_startTime').datetimebox('getValue');
	var endTime = $('#f_endTime').datetimebox('getValue');
	var joinNum = $('#f_joinNum').numberbox('getValue');
	var visitNum = $('#f_visitNum').numberbox('getValue');
	
	var userId = $('#f_userId').val();
	var instId = $('#f_instId').val();
	
	var auctionQuick = {
		auctionSerial:auctionSerial,
		auctionName:auctionName,
		/*bail:bail,
		spreadPackets:spreadPackets,*/
		startTime:startTime,
		endTime:endTime,
		joinNum:joinNum,
		visitNum:visitNum,
		userId:userId,
		instId:instId
	};
	if(id){//有id为更新，无id为新增
		auctionQuick.id = id;
	}
	return auctionQuick;
}

/** 设置用户信息的字段值 */
function setAuctionQuick(data){
	$('#f_auctionSerial').textbox('setValue', data.auctionSerial);
	//$('#f_bail').numberbox('setValue', data.bail);
	$('#f_auctionName').textbox('setValue',data.auctionName);
	//$('#f_spreadPackets').numberbox('setValue', data.spreadPackets);
	$('#f_startTime').datetimebox('setValue', formatDate(data.startTime,1));
	$('#f_endTime').datetimebox('setValue', formatDate(data.endTime,1));
	$('#f_joinNum').numberbox('setValue', data.joinNum);
	$('#f_visitNum').numberbox('setValue', data.visitNum);
	$('#filePaths').val(data.picPaths);
	
	refreshStatus(data);//设置状态下拉列表
	
	//查询产生的只读字段：
	$('#f_serial').textbox('setValue', data.instSerial);
	$('#f_instName').textbox('setValue', data.instName);
	$('#f_username').textbox('setValue', data.username);
	$('#f_userId').val(data.userId);//隐藏字段-用户ID
	$('#f_instId').val(data.instId);//隐藏字段-机构ID
	//以下为只读字段：
}

function refreshStatus(data){
	if(!data){
		data = {};
		data.startTime = $('#f_startTime').datetimebox('getValue');
		data.endTime = $('#f_endTime').datetimebox('getValue');
	}
	var mainStatus;
	if(data.endTime){
		mainStatus = 3;//已结束
	}else if((new Date(data.startTime)) < (new Date())){
		mainStatus = 2;//正在进行中
	}else{
		mainStatus = 1;//预展中
	}
	var $status = $('#f_mainStatus');
	$status.combobox('setValue', mainStatus);
	$status.combobox('readonly',true);//设置只读
}

function search(typeId){
	$('#datagrid').datagrid('load',{
		typeId : typeId
	});
}

function initSearch(){
	
	$('#sc_mainStatus').combobox({
		valueField : 'id',
		textField : 'name',
		editable : false,
		multiple:false,
	    required:false,
	    panelHeight:'auto',
		data : [{
			'id' : 1,
			'name' : '已结束'
			
		},{
			'id' : 2,
			'name' : '预展中'
		},{
			'id' : 3,
			'name' : '正在进行中'
		}]
	});
	
}


/**根据查询条件查询匹配的数据*/
function doSearch(){
	var sc_auctionSerial = $('#sc_auctionSerial').textbox('getValue');
	var sc_instName = $('#sc_instName').textbox('getValue');
	var sc_mainStatus = $('#sc_mainStatus').combobox('getValue');
	
	var sc_startTimeFrom = $('#sc_startTimeFrom').datebox('getValue');
	var sc_startTimeTo = $('#sc_startTimeTo').datebox('getValue');
	if(sc_startTimeFrom && !sc_startTimeTo){
		sc_startTimeTo = sc_startTimeFrom;
	}
	if(!sc_startTimeFrom && sc_startTimeTo){
		sc_startTimeFrom = sc_startTimeTo;
	}

	if(!sc_mainStatus){sc_mainStatus=""}
	
	var common_queryObj = GRID_QUERYOBJ;
	common_queryObj.serialLike = sc_auctionSerial;
	common_queryObj.instNameLike = sc_instName;
	common_queryObj.mainStatusSelf = sc_mainStatus;
	common_queryObj.startTimeFrom = sc_startTimeFrom;
	common_queryObj.startTimeTo = sc_startTimeTo;
	
	$('#datagrid').datagrid('load',common_queryObj);  
}
/**重置查询查询条件*/
function clearSearch(){
	$('#sc_auctionSerial,#sc_instName').textbox('reset');
	$('#sc_mainStatus').combobox('reset');
	$('#sc_startTimeFrom,#sc_startTimeTo').datebox('reset');
	
	
}

/** 查询拍卖机构的拍卖状态数据（检查机构是否有正在进行或预展中的拍卖） */
function getInstAuctionStatus(instId){
	if(!instId)return;
	$.post('/back/getAuctionQuickInstList',{instId:instId,endTimeNull:1},function(rsp){
		 if(rsp.success){
			var rows = rsp.rows;
			if(rows){
				var length = rows.length;
				if(length>0){
					$.messager.confirm('提示','该机构还有【'+length+'】场拍卖未结束，是否确定继续添加？',function(r){
						if(!r){
							closeAuctionQuickWin();
						}
					});
				}
			}
		 }else{
			 $.messager.alert('提示',rsp.msg);
		 }
	},'json');
	
}

/** 成功查询拍卖机构的自定义回调方法，主要是为了检查机构的拍卖状态 */
function afterSearchInst(inst){
	$('#f_serial').textbox('setValue',inst.serial);
 	$('#f_instName').textbox('setValue',inst.name);
 	$('#f_username').textbox('setValue',inst.username);
 	$('#f_userId').val(inst.userId);
 	$('#f_instId').val(inst.id);
 	getInstAuctionStatus(inst.id);
}

function searchInst(){
	searchAuctionQuickInstBySerial(afterSearchInst);//common_back:通用跟据机构编号查询机构
}

/** 跳转到 修改用户 页面 */
/**function jumpToAuctionQuickUpdate(){}*/
/** 跳转到 用户详情 页面 */
/**function jumpToAuctionQuick(){}*/

/** 批量删除用户 */
function batchDelete(){
	commonBatchDelete('/back/updateAuctionQuickDelete');//common_back:通用批量删除
}

/** 切换到回收站 */
function showTrach(){
	IS_SHOW_TRASH = true;
	commonShowTrash('#batchRecover,#batchThoroughDelete,#returnBack','#batchDelete,#addAuctionQuick,#userInfoLink,#auctionInstLink,#showTrash');
}

/** 从回收站返回 */
function returnBack(){
	IS_SHOW_TRASH = false;
	commonReturnBack('#batchDelete,#addAuctionQuick,#userInfoLink,#auctionInstLink,#showTrash','#batchRecover,#batchThoroughDelete,#returnBack');
}

/** 批量恢复用户 */
function batchRecover(id){
	commonBatchRecover('/back/updateAuctionQuickRecover',null,id);//common_back:通用批量恢复
}

/** 批量强制删除用户 */
function batchThoroughDelete(id){
	commonBatchThoroughDelete('/back/deleteAuctionQuickThorough',null,id);//common_back:通用批量强制删除
}

/** 跳转：用户信息 */
function jumpToUserInfo(){
	var url = "/back/userInfo";
	var id = $('#userId').val();
	if(id){
		url += "?userId="+id;
	}
	subShowMain('用户信息', url)
}

/** 跳转：拍卖机构 */
function jumpToAuctionQuickInst(){
	var url = "/back/auctionQuickInst";
	var id = $('#userId').val();
	if(id){
		url += "?userId="+id;
	}
	subShowMain('即时拍机构', url)
}

/** 跳转：藏品 */
function jumpToGoods(){
	var url = "/back/goods";
	var id = $('#userId').val();
	if(id){
		url += "?userId="+id;
	}
	subShowMain('藏品', url)
}

/** 跳转：新增或修改 */
function jumpToAuctionQuickAddOrUpdate(id){
	var url = "/back/auctionQuickAddOrUpdate";
	if(id){
		url += "?auctionQuickId="+id;
	}
	window.location.href = url;
}

